require 5.006;
package Chimera::Memcached;
use strict;
use Socket;
use IO::Poll qw(POLLIN POLLOUT POLLHUP POLLERR);
use Errno qw(EWOULDBLOCK);

my $poll = IO::Poll->new();
#$poll->mask($sock => POLLIN|POLLOUT);

sub new {
	my ($class, $host, $port) = @_;
	return bless({_host     => $host,
				  _port     => $port,
				  _conn     => {},
	              _max_conn => 50}, $class);
}

sub get {
	my $self = shift;
	my $key  = shift;
	
	my $conn = $self->_prepare_conn();
	if (defined $conn) {
		$self->{_conn}{$conn}{conn} = $conn;
		push @{$self->{_conn}{$conn}{write_buf}}, $key;
	}
}

sub _prepare_conn {
	my $self = shift;
	my $conn = undef;

	if (scalar(keys %{$self->{_conn}}) < $self->{_max_conn}) {
		my $proto = getprotobyname('tcp') || die("getprotobyname() failed: $!");
		socket($conn, AF_INET,SOCK_STREAM, $proto) or die("socket() failed: $!");
		my $pack_addr = inet_aton($self->{_host}) or die("inet_aton() failed: $self->{_host}");
		my $sock_addr = sockaddr_in($self->{_port}, $pack_addr);
		connect($conn, $sock_addr);
		$poll->mask($conn => POLLOUT);
		return $conn;
	} else {
		return 'asd';
	}
}

sub process {
	my $self = shift;
	
	$poll->poll();
	
	for ($poll->handles(POLLIN|POLLHUP|POLLERR)) {
		print 'in';
	}
	
	for my $conn ($poll->handles(POLLOUT|POLLERR)) {
		my $rc = syswrite($conn, @{$self->{_conn}{$conn}{write_buf}}[0]);
		if (defined $rc) {
			if ($rc > 0) {
				substr(@{$self->{_conn}{$conn}{write_buf}}[0], 0, $rc) = '';
			}
			print @{$self->{_conn}{$conn}{write_buf}}[0];
			exit;
		}
	}
}

1;